package itsec1.api.cardmanagement;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;

import javax.net.SocketFactory;

import itsec1.customermanagement.CustomerManagement;

public class CardManagementCaller {
	private static final String CARD_HOST= "localhost"; 
	
	public static String sendRequest(String request){
		String response= null;
		
		SocketFactory sf= CustomerManagement.createSocketFactory("keys/cardtruststore.jks");
		Socket socket = null;
		BufferedWriter out=null;
		BufferedReader in=null;
		
		try {
			socket= sf.createSocket(CardManagementCaller.CARD_HOST, CustomerManagement.CARDREQUEST_TCP_PORT);
			
			out = new BufferedWriter(new OutputStreamWriter(
					socket.getOutputStream()));
			in = new BufferedReader(new InputStreamReader(
					socket.getInputStream()));
			
			out.write(request);
			out.newLine();
			out.flush();

			response = in.readLine();
		}catch (Exception e) {
			System.out.println("Couldn't send request to card service");
			e.printStackTrace();
		}finally{
			//clean up
			if(in != null)
				try{
					in.close();
				}catch(IOException e1) {}
			if(out != null)
				try {
					out.close();
				}catch(IOException e1) {}
			if(socket != null && !socket.isClosed())
				try{
					socket.close();
				}catch(IOException e) {}
			
		}		
		return response;
	}
}
